using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

using Supremacy.Annotations;
using Supremacy.Client.Context;
using Supremacy.Game;

namespace Supremacy.Client.Services
{
    internal sealed class PlayerOrderService : IPlayerOrderService
    {
        private readonly IClientContext _clientContext;
        private readonly List<Order> _orders;

        public PlayerOrderService([NotNull] IClientContext clientContext)
        {
            if (clientContext == null)
                throw new ArgumentNullException("clientContext");
            _clientContext = clientContext;
            _orders = new List<Order>();
        }

        #region Implementation of IPlayerOrderService
        public ReadOnlyCollection<Order> Orders
        {
            get { return _orders.AsReadOnly(); }
        }

        public void AddOrder(Order order)
        {
            if (order == null)
                return;

            var localPlayer = _clientContext.LocalPlayer;
            if (localPlayer == null)
                return;

            var owner = localPlayer.Empire;
            if (owner == null)
                return;

            order.Owner = owner;

            lock (_orders)
            {
                while ((_orders.Count > 0) && order.Overrides(_orders[_orders.Count - 1]))
                    _orders.RemoveAt(_orders.Count - 1);
                _orders.Add(order);
            }
        }

        public bool RemoveOrder(Order order)
        {
            if (order == null)
                return false;
            lock (_orders)
            {
                return _orders.Remove(order);
            }
        }

        public void ClearOrders()
        {
            lock (_orders)
            {
                _orders.Clear();
            }
        }
        #endregion
    }
}